package com.t2t.top.framework.util.page;

/**
 * Created by yangpengfei on 2016/3/4.
 * 备注：11,1000,1000 意思是11页，1000开始,1000结束，执行数量1条
 * 为了方便记忆，构建数组的时候，开始和结束都包含。
 */
public class Page {

    private int currentPage = 1; // 实际页号

    private int pageSize; // 每页记录数

    private int total = 0; // 总记录数

    private int totalPages;

    private int begin;//查询开始，索引

    private int end;//查询结束，索引

    public int getBegin() {
        return begin;
    }

    public void setBegin(int begin) {
        this.begin = begin;
    }

    public int getEnd() {
        if (end > getTotal()) {
            return getTotal() - 1;
        }
        return end;
    }

    public void setEnd(int end) {
        this.end = end;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    public Page(int currentPage, int countNumbers, int pageSize) {
        try {
            setTotal(countNumbers);
            setPageSize(pageSize);
            setCurrentPage(currentPage);

            if (pageSize > countNumbers) {
                this.currentPage = 1;
            }

            int pg = this.currentPage;
            int fromIndex = 0;
            if (total != 0) {
                pg = pg - 1;
                fromIndex = pg * pageSize + 1;
            }
            int toIndex = fromIndex + pageSize - 1;
            if (toIndex > total) {
                toIndex = total;
            }
            if (toIndex < 0) {
                toIndex = 0;
            }
            int temp = fromIndex - 1;
            if (temp < 0) {
                temp = 0;
            }
            if (this.currentPage == 0) {
                this.currentPage = 1;
            }

            setTatalPages(countNumbers, pageSize);

            int begin = pageSize * (this.currentPage - 1);
            int end = pageSize * this.currentPage - 1;
            setBegin(begin);
            setEnd(end);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取总页数 （页数从1 开始）
     */
    private void setTatalPages(int countNumbers, int pageSize) {
        int totalPages = 1;
        if (countNumbers <= pageSize) {
            totalPages = 1;
        }
        if (countNumbers % pageSize == 0) {// 页数刚好是条数的总倍数
            totalPages = (countNumbers / pageSize);
        } else {
            totalPages = (countNumbers / pageSize) + 1;// 页数不是总条数的倍数
        }
        this.totalPages = totalPages;
    }
}
